package com.cqupt.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.cqupt.mapper.ProblemMapper;
import com.cqupt.mapper.TriggerMapper;
import com.cqupt.pojo.Trigger;
import com.cqupt.service.ProblemService;
import com.cqupt.service.ReportExportService;
import com.cqupt.utils.*;
import com.cqupt.utils.BaiduTransUtil.TransApi;
import com.sun.org.apache.bcel.internal.generic.PUTFIELD;
import com.sun.org.apache.xpath.internal.objects.XObject;
import com.sun.org.apache.xpath.internal.objects.XObjectFactory;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.rmi.PortableRemoteObject;
import javax.swing.*;
import javax.swing.plaf.basic.BasicTreeUI;
import java.rmi.MarshalledObject;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 告警接口实现类
 **/
@Service
public class ProblemServiceImpl implements ProblemService {

    private static final int ACTION_CLOSE_PROBLEM = 1;
    private static final int ACTION_ACKNOWLEDGE_EVENT = 2;
    private static final int ACTION_ADD_MESSAGE = 4;
    private static final int ACTION_CHANGE_SEVERITY = 8;
    private static final int ACTION_UNACKNOWLEDGE_EVENT = 16;
    private static List<String> objectList = new ArrayList();

    private TriggerMapper triggerMapper;
    @Autowired
    private ProblemMapper problemMapper;

    @Autowired
    private ReportExportService reportExportService;

    @Autowired
    public void setTriggerMapper(TriggerMapper triggerMapper) {
        this.triggerMapper = triggerMapper;
    }

    /**
     * @see ProblemService#getUnhandledProblems(String, String, String, String,String )
     * @param severities 选择的严重等级
     * @param hostIds 选择的hostIds
     * @param curPage 选择的当前页
     * @param pageSize 每页大小
     * @param objectid
     * @return
     */
    @Override
    public Map<String, Object> getUnhandledProblems(String severities, String hostIds, String curPage, String pageSize,String objectid) {
        final String token = APIUtils.getToken();
        // 拿到API数据
//        List<Map<String, Object>> problemDataList = getProblems(token, false, severities, hostIds, "");
        List<Map<String, Object>> problemDataList = getAllCurrentUnhandledProblems(token, severities, hostIds);
        if (objectid!=null)
            objectList.add(objectid);

        if (objectList!=null)
            for (int i = 0; i < problemDataList.size(); i++) {
                for (int j = 0; j < objectList.size(); j++) {
                    if (objectList.get(j).equals(problemDataList.get(i).get("objectid").toString())){
                        problemDataList.remove(i);
                        i--;
                        break;
                    }
                }
            }
        //去重
        for (int i = 0; i < problemDataList.size(); i++) {
            int j = i+1;
            for (; j < problemDataList.size(); j++) {
                if (problemDataList.get(i).get("host").toString().equals(problemDataList.get(j).get("host").toString()) &&
                        problemDataList.get(i).get("name").toString().equals(problemDataList.get(j).get("name").toString()) &&
                        !(problemDataList.get(i).get("clock").toString().equals(problemDataList.get(j).get("clock").toString()))
                )
                    break;
                if (problemDataList.get(i).get("host").toString().equals(problemDataList.get(j).get("host").toString()) &&
                        problemDataList.get(i).get("name").toString().equals(problemDataList.get(j).get("name").toString()) &&
                        problemDataList.get(i).get("clock").toString().equals(problemDataList.get(j).get("clock").toString())
                )
                    break;
            }
            if (j!=problemDataList.size()){
                problemDataList.remove(j);
                i--;
            }
        }
        // 记录总数据
        final int dataNum = problemDataList.size();
        Map<String, String> initHostItem = TextUtils.getTriggerDataToMap();
        // 分页
        problemDataList = PageUtils.getDataListByCurPage(problemDataList, curPage, pageSize);
        for (Map<String, Object> dataMap : problemDataList) {
            // 格式化严重等级
            TextUtils.transformSeverity(dataMap, "severity");
            // 格式化是否知晓
//            TextUtils.transformAcknowledged(dataMap);
//            // 格式化来源
//            TextUtils.transformSource(dataMap);
            // 格式化问题出现时间
            DateUtils.formatListDate(dataMap, "clock");
            // 格式化内容
            String name = dataMap.get("name").toString();
            dataMap.put("name", initHostItem.get(name)==null?name:initHostItem.get(name));
            // 汉化name
            if (dataMap.get("name").toString().indexOf("Zabbix Server has been restarted")!=-1)
                dataMap.put("name","客户端已重新启动");
            else if (dataMap.get("name").toString().indexOf("has been restarted")!=-1)
                dataMap.put("name",dataMap.get("host")+" "+"已重新启动");
            else if (dataMap.get("name").toString().indexOf("The Memory Pages/sec is too high")!=-1)
                dataMap.put("name","内存页/秒太高");
            else {
                translateNameToChinese(dataMap);
                // 替换Zabbix字符串
                TextUtils.replaceString(dataMap, "Zabbix", "Client", "name");
            }
        }
        // 进行数据封装
        Map<String, Object> resMap = TextUtils.packDataToMap(problemDataList, dataNum);
//        System.out.println(resMap.toString());
        return resMap;
    }

    /**
     * @see ProblemService#getUnhandledProblemsCount()
     * @return
     */
    @Override
    public String[] getUnhandledProblemsCount() {
        final String token = APIUtils.getToken();

//        List<Map<String, Object>> problemDataList = getProblems(token, false, "", "", "");
        List<Map<String, Object>> problemDataList = getAllCurrentUnhandledProblems(token, "", "");
        String[] resArray = getKeyCount(problemDataList, "severity", 6);

        return resArray;
    }

    /**
     * 检测问题
     * @param token
     * @param severities
     * @param hostIds
     * @param dateStr
     * @param returnType
     * @return
     */
    public List<Map<String, Object>> getProblemsAndAcknowledgedProblems(String token,String severities, String hostIds, String dateStr,int returnType) {

//        System.out.println("\n getProblemsAndAcknowledgedProblems\n");
        // get api data  未确认问题
        List<Map<String, Object>> problemDataList1 = getProblems_new(false, severities, hostIds, dateStr);
        ArrayList<Map<String, Object>> unDealProblem = new ArrayList<>();
        ArrayList<Map<String, Object>> DealProblem = new ArrayList<>();
        //循环，判断问题状态
        for (int i = 0; i < problemDataList1.size(); i++) {

            //获取一个问题的最新消息
            List<Map<String, Object>> DataList = getProblemByObjectID(problemDataList1.get(i).get("objectid").toString());

            for (int j = i; j < problemDataList1.size(); j++) {
                //不是同一个问题
                if(!problemDataList1.get(j).get("objectid").equals(problemDataList1.get(i).get("objectid")))
                    continue;
                if (!DataList.isEmpty()) {
                    //最新的未确认问题，是未处理问题
                    if (DataList.get(0).get("eventid").equals(problemDataList1.get(j).get("eventid"))) {
                        //未处理问题列表
                        problemDataList1.get(j).put("status", "未处理");
                        unDealProblem.add(problemDataList1.get(j));
                    } else {

                        problemDataList1.get(j).put("status", "已关闭");
                        DealProblem.add( problemDataList1.get(j));
                        //对未确认的旧消息进行确认
                        //  String eventid = problemDataList1.get(j).get("eventid").toString();
                        // final Map<String, Object> resultMap = acknowledgeProblem(eventid, "旧消息");
                    }// jiu xiao xi
                } //未关闭问题
                else {// mei wenti  问题已经关闭了
                    problemDataList1.get(j).put("status", "已关闭");
                    DealProblem.add( problemDataList1.get(j));
                    //直接确认，原因是问题已关闭
                    // String eventid = problemDataList1.get(j).get("eventid").toString();
                    // final Map<String, Object> resultMap = acknowledgeProblem(eventid, "问题已关闭，系统自动确认知晓");
                }
                //状态判断完后，从队列里去除
                problemDataList1.remove(j);
                j--;
            }//for j
        } ///过滤
        if(returnType==0)
            return unDealProblem;
        else{
            //返回未确认的历史消息
            //
            return DealProblem;
        }
    }

    /**
     * @see ProblemService#getAcknowledgedProblems(String, String, String, String, String)
     */
    @Override
    public Map<String, Object> getAcknowledgedProblems(String severities, String hostIds, String dateStr, String curPage, String pageSize) {
        final String token = APIUtils.getToken();
//        System.out.println("\n getAcknowledgedProblems\n");
        // 拿到API数据  获取到状态未确认但是问题已经关闭或者没有关闭的旧消息
        List<Map<String, Object>> problemDataList1 = getProblemsAndAcknowledgedProblems(token,severities, hostIds, dateStr,1);

        // 拿到API数据 //获取已经确认过的消息
        List<Map<String, Object>> problemDataList = getProblems_new(true, severities, hostIds, dateStr);
        //消息合并按产生时间排序
        for (int i=0;i<problemDataList1.size();i++)
            problemDataList.add(problemDataList1.get(i));
        Collections.sort(problemDataList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Long name1 = Long.valueOf(o1.get("clock").toString()) ;
                Long name2 = Long.valueOf(o2.get("clock").toString()) ;
                return name2.compareTo(name1);
            }
        });
        //选取一部分数据
        if (problemDataList.size()>1000){
            problemDataList = problemDataList.subList(0,1000);
        }
        final int dataNum = problemDataList.size();
//        if ("".equals(severities) || "未分类,信息类,警告,一般严重,严重,灾难".equals(severities)){
//            String[] temp = getAcknowledgedProblemsCount_New(dateStr);
//            int sum = 0;
//            for (int i = 0; i < temp.length; i++) {
//                sum += Integer.valueOf(temp[i]);
//            }
//            dataNum = sum;
//        }
        // 分页
        problemDataList = PageUtils.getDataListByCurPage(problemDataList, curPage, pageSize);
        // 对返回的数据进行处理，便于前端展示
        for (int i = 0; i < problemDataList.size(); i++) {
            if (problemDataList.get(i).get("status").equals("已处理") || problemDataList.get(i).get("status").equals("已关闭"))
                continue;
            Map<String, Object> resmap = getSolutionByEventId(problemDataList.get(i).get("eventid").toString());
            Map<String, Object>acknowledges = (Map<String, Object>) resmap.get("result");

            if (acknowledges.get("message").equals("此告警项已被忽略")) {
                problemDataList.get(i).put("status", "已忽略");
            } else {
                List<Map<String, Object>> DataList = getProblemByObjectID(problemDataList.get(i).get("objectid").toString());
                if (!DataList.isEmpty()) {
                    //
                    if (problemDataList.get(i).get("eventid").equals(DataList.get(0).get("eventid")))
                        problemDataList.get(i).put("status", "已处理");
                    else
                        problemDataList.get(i).put("status", "已关闭");
                } else {
                    problemDataList.get(i).put("status", "已关闭");
                }
            }

        }//end for



        // 以下代码格式化数据，汉化返回结果
        Map<String, String> initHostItem = TextUtils.getTriggerDataToMap();
        for (Map<String, Object> dataMap : problemDataList) {
            //格式化问题状态


            // 格式化严重等级
            TextUtils.transformSeverity(dataMap, "severity");
            // 格式化是否知晓
            TextUtils.transformAcknowledged(dataMap);
            // 格式化来源
            TextUtils.transformSource(dataMap);
            // 格式化问题出现时间
            DateUtils.formatListDate(dataMap, "clock");
            // 格式化内容
            String name = dataMap.get("name").toString();
            dataMap.put("name", initHostItem.get(name)==null?name:initHostItem.get(name));
            // 汉化name
            if (dataMap.get("name").toString().indexOf("Zabbix Server has been restarted")!=-1)
                dataMap.put("name","客户端已重新启动");
            else if (dataMap.get("name").toString().indexOf("has been restarted")!=-1)
                dataMap.put("name",dataMap.get("host")+" "+"已重新启动");
            else if (dataMap.get("name").toString().indexOf("The Memory Pages/sec is too high")!=-1)
                dataMap.put("name","内存页/秒太高");
            else {
                translateNameToChinese(dataMap);
                // 替换Zabbix字符串
                TextUtils.replaceString(dataMap, "Zabbix", "Client", "name");
            }
        }

        Map<String, Object> resMap = TextUtils.packDataToMap(problemDataList, dataNum);
//        System.out.println("\n getAcknowledgedProblems end\n");
        return resMap;
    }


    /**
     * @see ProblemService#getAcknowledgedProblemsCount()
     */
    @Override
    public String[] getAcknowledgedProblemsCount() {
        final String token = APIUtils.getToken();
        List<Map<String, Object>> problemDataList1 = getProblems_new( true, "", "", "");
        List<Map<String, Object>> problemDataList = getProblems_new( false, "", "", "");
        for (int i=0;i<problemDataList1.size();i++)
            problemDataList.add(problemDataList1.get(i));
        if (problemDataList.size()>1000)
            problemDataList = problemDataList.subList(0,1000);
        String[] resArray = getKeyCount(problemDataList, "severity", 6);

        return resArray;
    }

    /**
     * 获取所有历史警告的分类统计
     * @param dateStr 日期字符串
     * @return 历史警告的分类统计
     */
    @Override
    public String[] getAcknowledgedProblemsCount(String dateStr) {
        final String token = APIUtils.getToken();
        // 获取不同确认状态的历史告警
//        List<Map<String, Object>> problemDataList1 = getProblems(token, true, "", "", dateStr);
        List<Map<String, Object>> problemDataList1 = getProblemsAndAcknowledgedProblems(token,"", "", dateStr,1);
        List<Map<String, Object>> problemDataList = getProblems_new(true, "", "", dateStr);
        for (int i=0;i<problemDataList1.size();i++)
            problemDataList.add(problemDataList1.get(i));
        Collections.sort(problemDataList, new Comparator<Map<String, Object>>() {
            public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                Long name1 = Long.valueOf(o1.get("clock").toString()) ;
                Long name2 = Long.valueOf(o2.get("clock").toString()) ;
                return name2.compareTo(name1);
            }
        });
        if (problemDataList.size()>1000)
            problemDataList = problemDataList.subList(0,1000);
        // 根据严重性获取分类统计结果
        String[] resArray = getKeyCount(problemDataList, "severity", 6);
        return resArray;
    }
    @Override
    public String[] getAcknowledgedProblemsCount_New(String severities, String hostIds,String dateStr) {
        String[] resArray = {"0","0","0","0","0","0"};
        int[] temp = new int[6];
        Map<String, Object> map = getAcknowledgedProblems(severities,hostIds,dateStr,"1","1000");
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("result");
        for (int i = 0; i < list.size(); i++) {
            Map<String, Object> tmp = list.get(i);
            switch (tmp.get("severity").toString()){
                case "未分类":
                    temp[0]++;
                    break;
                case "信息类":
                    temp[1]++;
                    break;
                case "警告":
                    temp[2]++;
                    break;
                case "一般严重":
                    temp[3]++;
                    break;
                case "严重":
                    temp[4]++;
                    break;
                case "灾难":
                    temp[5]++;
                    break;
            }
        }
        for (int i = 0; i < temp.length; i++) {
            resArray[i]= String.valueOf(temp[i]);
        }
        return resArray;
    }

    /**
     * @see ProblemService#acknowledgeProblem(String, String)
     */
    @Override
    public Map<String, Object> acknowledgeProblem(String eventId, String desc) {
        final String token = APIUtils.getToken();

        int action = ACTION_ACKNOWLEDGE_EVENT;
        if (!desc.isEmpty()) {
            // 如果写描述
//            System.out.println("没写描述");
            action += ACTION_ADD_MESSAGE;
        }
        // 更新event事件，更新确认字段
        List<Integer> resultList = updateEvent(token, eventId, action, desc, 0);
        Map<String, Object> resMap = new HashMap<String, Object>() {{
            put("status", "true");
        }};
        resMap.put("result", resultList);
        if (resultList == null || resultList.isEmpty()) {
            // 出现错误
            resMap.put("status", "false");
        }

        return resMap;
    }

    /**
     * @see ProblemService#closeProblem(String)
     */
    @Override
    public Map<String, Object> closeProblem(String eventId) {
        final String token = APIUtils.getToken();

        List<Integer> resultList = updateEvent(token, eventId, ACTION_CLOSE_PROBLEM, null, 0);
        Map<String, Object> resMap = new HashMap<String, Object>() {{
            put("status", "true");
        }};
        resMap.put("result", resultList);

        if (resultList == null || resultList.isEmpty()) {
            // 出现错误
            resMap.put("status", "false");
        }

        return resMap;
    }

    @Override
    public Map<String, Object> getSolutionByEventId(String eventid) {
        final String token = APIUtils.getToken();
        // 封装查询参数
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("output", "extend");
            put("eventids", eventid);    // 根据严重等级筛选
            put("select_acknowledges","extend");
        }};
        // 填入最终参数
        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};

        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
//        System.out.println("\n  getSolutionByEventId:"+JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue)+",\n result="+responseMap
//        );
        Map<String, Object> resMap = new HashMap<String, Object>() {{
            put("status", "true");
        }};

        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");

        if (resultList == null || resultList.isEmpty()) {
            // 出现错误
            resMap.put("status", "false");
        }else{//modify by dzz
            Map<String, Object> res_cur = resultList.get(0);
            List<Map<String, Object>> acknowledges = (List<Map<String, Object>>) res_cur.get("acknowledges");
            //cknowledges 可能为空，比如自动关闭的告警， 报BUG
            if(acknowledges.size()==0){
                resMap.put("result", "");
            }
            //action 1 close   action 2+4 shi que ren 先确认后关闭有个关闭操作。去掉关闭操作
            else if((acknowledges.size()>1)&&(acknowledges.get(0).get("action").equals("1"))){
                resMap.put("result", acknowledges.get(1));
            }else{
                resMap.put("result", acknowledges.get(0));
            }

            resMap.put("data_num", "1");
        }
//        System.out.println(resMap);
        return resMap;
    }

    /**
     * （已废置）通过严重等级和主机获取当前未处理的警告
     * <p>
     * 先通过problem.get获取当前未处理problem记录
     * 再通过problem记录的eventid字段获取event记录，其中联结查询host得到host相关信息
     *
     * @param token      密钥
     * @param severities 严重等级
     * @param hostIds    主机
     * @return 存储以Map封装每条信息的List
     */
    @Override
    public List<Map<String, Object>> getAllCurrentUnhandledProblems(String token, String severities, String hostIds) {
        final String[] outputs = new String[]{
                "object", "objectid", "clock", "name", "r_eventid", "severity"
        };

        final Map<String, String> searchMap = new HashMap<String, String>() {{
            put("r_eventid", "0");  // 筛选出尚未解决的问题
        }};

        // 填入params的对应参数
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("output", outputs);
            put("severities", TextUtils.revertSeverity(severities));    // 根据严重等级筛选
            put("acknowledged", false);     // 筛选未被确认的问题
            put("sortfield", "eventid");
            put("sortorder", "DESC");
            put("filter", new HashMap<String, Object>() {{
                put("searchByAny", true);   // 开启筛选
                put("search", searchMap);    // 具体筛选，规则为LIKE "%...%"
                put("startSearch", true);    // 从头开始搜索
            }});
        }};

        // 筛选主机
        if (!(hostIds == null || hostIds.isEmpty())) {
            String[] temp = hostIds.split(",");
            paramsMap.put("hostids", temp);
        }

        // 填入最终参数
        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "problem.get");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};

        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");

        // 继续查询host数据
        // 应该先分页再查询
        String[] eventidArray = new String[resultList.size()];
        for (int i = 0; i < resultList.size(); i++) {
            Map<String, Object> tempMap = resultList.get(i);
            eventidArray[i] = (String) tempMap.get("eventid");
        }

        final String[] selectHosts = new String[]{"host"};

        Map<String, Object> eventParamsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("eventids", eventidArray);
                put("selectHosts", selectHosts);
                put("sortfield", "eventid");    // 与前面的problem.get排序规则相同
                put("sortorder", "DESC");   // 同上
            }});
        }};
        Map<String, Object> hostsMap = APIUtils.sendRequest(JSON.toJSONString(eventParamsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> hostsList = (List<Map<String, Object>>) hostsMap.get("result");

        // 将查到的host值放到之前的resultList内每条Map记录中
        for (int i = hostsList.size()-1; i >= 0; i--) {
            Map<String, Object> tempMap = hostsList.get(i);
            JSONArray tempArray = (JSONArray) tempMap.get("hosts");
            if (tempArray.isEmpty()) {
                // 该事件的主机已被删除
                resultList.remove(i);
            } else {
                // 该事件的主机存在
                Map<String, Object> innerMap = tempArray.getJSONObject(0);
                resultList.get(i).put("hostid", innerMap.get("hostid"));
                resultList.get(i).put("host", innerMap.get("host"));
            }
        }

        return resultList;
    }

    /**
     * 根据严重等级和时间获取所有历史警告
     *
     * @param token      API请求令牌
     * @param severities 选择的严重等级
     * @param acknowledged  是否已确认
     * @param hostIds 选择的主机ID
     * @param dateStr    选择的时间范围
     * @return 存储以Map封装每条信息的List
     */
    @Override
    public List<Map<String, Object>> getProblems(String token, boolean acknowledged, String severities, String hostIds, String dateStr) {
        long startTemp = 0L;
        long endTemp = new Date().getTime();
        if (!(dateStr == null || dateStr.isEmpty())) {
            // dateStr不为空
            String[] dateArray = dateStr.split(",");
//            startTemp = DateUtils.toTimeStamp(dateArray[0]);
            startTemp = Long.parseLong(dateArray[0])/1000;
//            endTemp = DateUtils.toTimeStamp(dateArray[1]);
            endTemp = Long.parseLong(dateArray[1])/1000;
        }
        final long startDate = startTemp;
        // 截止天数包括当天，因此加上一天的秒数
//        final long endDate = endTemp + (60 * 60 * 24);
        final long endDate = endTemp;

        final String[] outputs = new String[]{
                "object", "objectid", "severity", "acknowledged", "clock", "name", "source"
        };
        final String[] selectHostsParams = new String[]{"host"};
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("selectHosts", selectHostsParams);
            put("output", outputs);
            put("severities", TextUtils.revertSeverity(severities));
            put("value", 1);    // 1代表历史告警
            put("acknowledged", acknowledged);
            put("time_from", startDate);
            put("time_till", endDate);
            put("sortfield", "clock");
            put("sortorder", "DESC");
        }};
//        if (acknowledged){
//            // 筛选是否已确认
//            paramsMap.put("acknowledged", true);
//        }
        if (!(hostIds == null || hostIds.isEmpty())) {
            // 筛选主机
            String[] temp = hostIds.split(",");
            paramsMap.put("hostids", temp);
        }
        // 填入参数
        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
//        for (Map<String, Object> stringObjectMap : resultList) {
//            JSONArray jsonValues = (JSONArray) stringObjectMap.get("hosts");
//            if (jsonValues.isEmpty()) {
//                JSONObject jsonObject = new JSONObject();
//                jsonObject.put("host", "该主机已被删除");
//                jsonObject.put("hostid", "没有主机ID");
//                jsonValues.add(jsonObject);
//            }
//        }

        for (int i = resultList.size()-1; i >= 0; i--) {
            JSONArray jsonValues = (JSONArray) resultList.get(i).get("hosts");
            if (jsonValues.isEmpty()) {
                // 该事件的主机已被删除
                resultList.remove(i);
            } else {
                // 该事件的主机存在
                Map<String, Object> innerMap = jsonValues.getJSONObject(0);
                resultList.get(i).put("hostid", innerMap.get("hostid"));
                resultList.get(i).put("host", innerMap.get("host"));
                resultList.get(i).put("status","" );
            }
        }
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getProblems_new(boolean acknowledged,String severities, String hostIds, String dateStr) {

        DemoServiceImpl demoService = new DemoServiceImpl();
        Map<String,String> serv = new HashMap<>();
        serv.put("未分类","0");
        serv.put("信息类","1");
        serv.put("警告","2");
        serv.put("一般严重","3");
        serv.put("严重","4");
        serv.put("灾难","5");

        if(dateStr == null){
            Date d1 = new Date();
            dateStr = "1340934596000,"+d1.getTime();
        }
        String[] dateArray = dateStr.split(",");
        String startDate = ""+Long.parseLong(dateArray[0])/1000;
        String endDate = ""+Long.parseLong(dateArray[1])/1000;

        List<String> ack = new ArrayList<>();
        List<String> sever = new ArrayList<>();
        if (acknowledged)
            ack.add("1");
        else if (acknowledged == false){
            ack.add("0");
            ack.add("1");
        }
        List<String> hostids = new ArrayList<>();
        if (hostIds==""){
            List<Map<String, Object>> resultList = demoService.getAllOnlineHost();
            for (int i = 0; i < resultList.size(); i++) {
                hostids.add(resultList.get(i).get("hostid").toString());
            }
        }else {
            String[] hos = hostIds.split(",");
            for (int i = 0; i < hos.length; i++) {
                hostids.add(hos[i]);
            }
        }
        if(severities==""){
            sever.add("0");
            sever.add("1");
            sever.add("2");
            sever.add("3");
            sever.add("4");
            sever.add("5");
        }else {
            String[] s = severities.split(",");
            for (int i = 0; i < s.length; i++) {
                sever.add(serv.get(s[i]));
            }

        }

        List<Map<String, Object>> result = problemMapper.getProblems_new(startDate,endDate,hostids,ack,sever);
        List<Map<String, Object>> response = new ArrayList<>();

        if (acknowledged){
            for (int i = 0; i < result.size(); i++) {
                Map<String, Object> map = result.get(i);
                Map<String, Object> res = new HashMap<>();
                res.put("host",map.get("host"));
                res.put("hostid",map.get("hostid").toString());
                JSONObject json = new JSONObject(res);
                List<Map<String, Object>> temp = new ArrayList<>();
                temp.add(json);
                map.put("severity",map.get("severity").toString());
                map.put("eventid",map.get("eventid").toString());
                map.put("acknowledged",map.get("acknowledged").toString());
                map.put("hosts",temp);
                map.put("name",map.get("name").toString());
                map.put("host",map.get("host").toString());
                map.put("hostid",map.get("hostid").toString());
                map.put("clock",map.get("clock").toString());
                map.put("source",map.get("source").toString());
                map.put("objectid",map.get("objectid").toString());
                map.put("object",map.get("object").toString());
                map.put("status","");

                response.add(new JSONObject(map));
            }
        }else {
            for (int i = 0; i < result.size(); i++) {
                Map<String, Object> map = result.get(i);
                Map<String, Object> res = new HashMap<>();
                res.put("host",map.get("host"));
                res.put("hostid",map.get("hostid").toString());
                JSONObject json = new JSONObject(res);
                List<Map<String, Object>> temp = new ArrayList<>();
                temp.add(json);
                map.put("severity",map.get("severity").toString());
                map.put("eventid",map.get("eventid").toString());
                map.put("acknowledged",map.get("acknowledged").toString());
                map.put("hosts",temp);
                map.put("name",map.get("name").toString());
                map.put("host",map.get("host").toString());
                map.put("hostid",map.get("hostid").toString());
                map.put("clock",map.get("clock").toString());
                map.put("source",map.get("source").toString());
                map.put("objectid",map.get("objectid").toString());
                map.put("object",map.get("object").toString());
                map.put("status","");

                response.add(new JSONObject(map));
            }
        }

        return response;
    }
    /**
     * 统计严重等级的分类统计
     *
     * @param dataList 要统计的List
     * @param key      要统计的字段名
     * @param typeNum  要统计字段的类型数
     * @return 存储分类统计结果的字符串数组
     */
    private String[] getKeyCount(List<Map<String, Object>> dataList, String key, int typeNum) {
        int[] countArrays = new int[typeNum];
        for (Map<String, Object> dataMap : dataList) {
            // 统计
            countArrays[Integer.parseInt((String) dataMap.get(key))]++;
        }
        // 将int数组转为String数组
        String[] resDataArray = new String[typeNum];
        for (int i = 0; i < typeNum; i++) {
            resDataArray[i] = String.valueOf(countArrays[i]);
        }

        return resDataArray;
    }

    /**
     * 更新event事件
     *
     * @param token    API请求令牌
     * @param eventIds 要操作的eventids
     * @param action   位掩码，支持加法和
     * @param message  要添加的message
     * @param severity 新的severity
     * @return 影响的eventids，Integer列表
     */
    private List<Integer> updateEvent(String token, String eventIds, int action, String message, int severity) {
        // 参数封装
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("eventids", eventIds);
            put("action", action);
        }};

        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "event.acknowledge");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};
        // 传入阐述检查
        if(message != null & !"".equals(message)){
            paramsMap.put("message", message);
        }

        if (severity > 0) {
            paramsMap.put("severity", severity);
        }
        // 发送请求，获取结果
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
        JSONObject resultObject = (JSONObject) responseMap.get("result");

        // 返回的eventids值是Integer列表
        if(resultObject != null){
            return (List<Integer>) resultObject.get("eventids");
        }
        return null;
    }

    /**
     * 汉化name字段
     *
     * @param dataMap
     */
    public void translateNameToChinese(Map<String, Object> dataMap){
        if (dataMap.get("object").equals("0")) {
            Trigger trigger = null;
            try {
                Long temp = Long.parseLong((String) dataMap.get("objectid"));
                trigger = triggerMapper.findTriggerById(temp);
            } catch (Exception e){
                e.getMessage();
            }
            String desc = (String) dataMap.get("name");

            if (trigger != null) {
                // 拿到实参
                ArrayList<String> values = TextUtils.getActualValues(trigger.getDescription(), desc);

                String descZh = trigger.getDescriptionZh();
                // 将实参替换到汉化记录中
                for (String value : values) {
                    descZh = descZh.replaceFirst("\\{.*?\\{?.*?}?”?}", value);
                }

                dataMap.put("name", descZh);
            } else {
                // 为空表明是新添加的trigger
                String[] strHead = new String[]{"has", "runs", "uses"};   // 形参在头部
                String[] strTail = new String[]{"on", "is", "Critical"};  // 形参在尾部
                String[] strNoParams = new String[]{"75%", "power", "ICMP ping"};    // 没有形参的

                String regexpStr1 = "";
                boolean hasParams = true;
                boolean flag = true;

                // 先判断有无形参
                for (String s : strNoParams) {
                    if (desc.contains(s)) {
                        regexpStr1 = desc;
                        hasParams = false;
                        break;
                    }
                }
                if (hasParams) {
                    // 有形参
                    // 形参在尾部的，取头
                    for (String s : strTail) {
                        if (desc.contains(s)) {
                            regexpStr1 = desc.split(s)[0] + ".+";
                            flag = false;
                            break;
                        }
                    }
                    if (flag) {
                        // 形参在头部的，取尾
                        for (String s : strHead) {
                            if (desc.contains(s)) {
                                regexpStr1 = ".+" + desc.split(s)[1];
                                flag = false;
                                break;
                            }
                        }
                    }
                    if (flag) {
                        // 有两个冒号，取中间；只有一个冒号，取到结尾
                        if (desc.contains(":")) {
                            String[] strs = desc.split(":");
                            if (strs.length == 2) {
                                regexpStr1 = ".+" + strs[1];
                            } else {
                                regexpStr1 = ".+" + strs[1] + ".+";
                            }
                        }
                    }
                }

                List<Trigger> triggerList = new ArrayList<>();
                try {
                    triggerList = triggerMapper.findTriggersInDescByDescription(regexpStr1);
                } catch (Exception e){
                    e.getMessage();
                }

                if (!triggerList.isEmpty()) {
                    trigger = triggerList.get(0);
                    String descZh = trigger.getDescriptionZh();
                    if (hasParams){
                        // 需要将汉化语句中的形参替换成实参
                        ArrayList<String> values = TextUtils.getActualValues(trigger.getDescription(), desc);
                        if (values.isEmpty()){
                            TextUtils.replaceString(dataMap, "Zabbix", "Client", "name");
                        } else {
                            // 将实参替换到汉化记录中
                            for (String value : values) {
                                descZh = descZh.replaceFirst("\\{.*?\\{?.*?}?”?}", value);
                            }
                        }
                    }
                    dataMap.put("name", descZh);
                }
            }
        }
    }

    /**
     * 批量关闭告警项事件
     * @param eventids 事件id
     * @param action 关闭或者确认
     * @return
     */
    @Override
    public Map<String, Object> eventHandle(List<String> eventids, Integer action) {
        String token = APIUtils.getToken();

        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "event.acknowledge");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("eventids", eventids);
                put("action", action);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return (Map<String, Object>)responseMap.get("result");
    }

    /**
     * 获得与主机相关的告警项事件
     * @param hostid 主机id
     * @param acknowledged  返回事件是否被确认（false:未被确认的事件 true：已被确认的事件）
     * @return 告警事件项
     */
    @Override
    public Map<String, Object> getEventsByHostid(String hostid, Boolean acknowledged) {
        String token = APIUtils.getToken();

        // 输出过滤
        List<String> itemList = new ArrayList<>();
        itemList.add("eventids");
        itemList.add("source");
        itemList.add("acknowledged");// 事件是否被确认-Integer
        itemList.add("name");// 事件名称
        itemList.add("clock");// 事件创建事件


        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids", hostid);
                put("output", itemList);
                put("acknowledged",acknowledged);// 仅返回未被确认的事件
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }

    /**
     * 根据关机重启结果判断是否清空告警事件
     * @param hostid 宿主主机id
     * @param eventName 告警事件名称
     * @return
     */
    @Override
    public Map<String, Object> isClearEvent(String hostid, String eventName) {

//        List<Map<String, Object>> eventCurrent = new ArrayList<>();
        // 获取未确认告警项事件
        ProblemServiceImpl psi = new ProblemServiceImpl();
        Map<String, Object> eventResult = psi.getEventsByHostid(hostid,false);

        // 遍历取出指定名称对应的事件id,且value为1，即异常事件
        List<String> eventidList = new ArrayList<>();
        if(eventResult.get("result") != null){
            List<Map<String, Object>> eventList = (List<Map<String, Object>>)eventResult.get("result");

            if("".equals(eventName) || eventName == null){ // 确认所有事件
                for (int i = 0; i < eventList.size(); i++) {
                    if("1".equals(eventList.get(i).get("value"))){
                        eventidList.add((String)eventList.get(i).get("eventid"));
//                            eventCurrent.add(eventList.get(i));
                    }
                }
            } else { // 仅确认指定“name”的事件
                for (int i = 0; i < eventList.size(); i++) {
                    if(eventName.equals(eventList.get(i).get("name")) & "1".equals(eventList.get(i).get("value"))){
                        eventidList.add((String)eventList.get(i).get("eventid"));
//                            eventCurrent.add(eventList.get(i));
                    }
                }
            }
        }
//        System.out.println("当前待关闭的事件数量为："+eventidList.size());
//        System.out.println(eventCurrent);
        // 操作进行
        if(eventidList != null){
            return eventHandle(eventidList,ACTION_ACKNOWLEDGE_EVENT);
        }else{
            return null;
        }
    }


    /**
     *通过triggerid获得告警信息
     * @param trigger
     * @param host
     * @param hostid
     * @return
     */

    @Override
    public Map<String, Object> getEventByTriggerID(String trigger, String host, String hostid) {
        String token = APIUtils.getToken();
        // 输出过滤
        List<String> itemList = new ArrayList<>();
        itemList.add("source"); //事件产生来源
        itemList.add("name");// 事件名称
        itemList.add("clock");// 事件创建事件
        itemList.add("value");//事件状态 {0:ok 1:problem}
        itemList.add("severity");//事件的安全性
        itemList.add("acknowledged");//事件的确认状态
        itemList.add("object");//与事件对应的对象类型
        itemList.add("objectid");//相关对象id

        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("objectids", trigger);
                put("select_acknowledges","extend");
                put("output",itemList);
                put("sortfield","clock");
                put("sortorder","DESC");
            }});
        }};
        Map<String, Object> responseList = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));

        JSONArray array = (JSONArray) responseList.get("result");
        Map<String,Object> responseMap = new HashMap<>();
//        //遍历JSONArray
        for (Iterator iterator = array.iterator(); iterator.hasNext();) {
            JSONObject obj = (JSONObject)iterator.next();
            Map<String,Object> hosts = new HashMap<String, Object>(){{
                put("host",host);
                put("hostid",hostid);
            }};
            responseMap.put("host",host);
            responseMap.put("hostid",hostid);
            responseMap.put("hosts",hosts);
            Map<String,Object> temp = new HashMap<String, Object>(){{
                put("severity",obj.get("severity"));
            }};
            TextUtils.transformSeverity(temp, "severity");
            responseMap.put("severity",temp.get("severity"));
            responseMap.put("eventid",obj.get("eventid"));
            responseMap.put("acknowledged",obj.get("acknowledged"));
            Map<String,Object> temp1 = new HashMap<String, Object>(){{
                put("object",obj.get("object"));
                put("objectid",obj.get("objectid"));
                put("name",obj.get("name"));
            }};
            translateNameToChinese(temp1);
            TextUtils.replaceString(temp1, "Zabbix", "Client", "name");
            responseMap.put("name",temp1.get("name"));
            //时间转换问题
            Map<String,Object> temp2 = new HashMap<String, Object>(){{
//                Integer time = Integer.parseInt((String) obj.get("clock"))-18000;
//                String time_clock = String.valueOf(time);
                put("clock",obj.get("clock"));
            }};
            DateUtils.formatListDate(temp2, "clock");
            responseMap.put("clock",temp2.get("clock"));
            Map<String,Object> temp3 = new HashMap<String, Object>(){{
                put("source",obj.get("source"));
            }};
            TextUtils.transformSource(temp3);
            responseMap.put("source",temp3.get("source"));
            responseMap.put("objectid",obj.get("objectid"));
            responseMap.put("object",obj.get("object"));
        }
        return responseMap;
    }

    @Override
    public Map<String, Object> getEventByTriggerID(String serveries, String trigger, String host, String hostid) {
        String token = APIUtils.getToken();
        // 输出过滤
        List<String> itemList = new ArrayList<>();
        itemList.add("source"); //事件产生来源
        itemList.add("name");// 事件名称
        itemList.add("clock");// 事件创建事件
        itemList.add("value");//事件状态 {0:ok 1:problem}
        itemList.add("severity");//事件的安全性
        itemList.add("acknowledged");//事件的确认状态
        itemList.add("object");//与事件对应的对象类型
        itemList.add("objectid");//相关对象id

        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("objectids", trigger);
                put("select_acknowledges","extend");
                put("output",itemList);
                put("sortfield","clock");
                put("sortorder","DESC");
            }});
        }};
        Map<String, Object> responseList = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        JSONArray array = (JSONArray) responseList.get("result");
        String[] severList = serveries.split(",");
        Map<String,Object> responseMap = new HashMap<>();
//        //遍历JSONArray
        Iterator iterator = array.iterator();
        JSONObject obj = (JSONObject)iterator.next();
        Map<String,Object> temp = new HashMap<String, Object>(){{
            put("severity",obj.get("severity"));
        }};
        TextUtils.transformSeverity(temp, "severity");
        int j;
        for (j=0;j<severList.length;j++){
            if(temp.get("severity").toString().equals(severList[j]))
                break;
        }
        if(j>=severList.length)
            return null;
//            if (serveries.indexOf(temp.get("severity").toString())==-1)
//                return null;
        responseMap.put("severity",temp.get("severity"));
        responseMap.put("eventid",obj.get("eventid"));
        responseMap.put("acknowledged",obj.get("acknowledged"));
        Map<String,Object> temp1 = new HashMap<String, Object>(){{
            put("object",obj.get("object"));
            put("objectid",obj.get("objectid"));
            put("name",obj.get("name"));
        }};
        translateNameToChinese(temp1);
        TextUtils.replaceString(temp1, "Zabbix", "Client", "name");
        responseMap.put("name",obj.get("name"));
        Map<String,Object> temp2 = new HashMap<String, Object>(){{
//                Integer time = Integer.parseInt((String) obj.get("clock"))-18000;
//                String time_clock = String.valueOf(time);
            put("clock",obj.get("clock"));
        }};
        DateUtils.formatListDate(temp2, "clock");
        responseMap.put("clock",temp2.get("clock"));
        Map<String,Object> temp3 = new HashMap<String, Object>(){{
            put("source",obj.get("source"));
        }};
        TextUtils.transformSource(temp3);
        responseMap.put("source",temp3.get("source"));
        responseMap.put("objectid",obj.get("objectid"));
        responseMap.put("object",obj.get("object"));
        Map<String,Object> hosts = new HashMap<String, Object>(){{
            put("host",host);
            put("hostid",hostid);
        }};
        responseMap.put("host",host);
        responseMap.put("hostid",hostid);
        responseMap.put("hosts",hosts);
        return responseMap;
    }

    /**
     * 通过hostid获得triggerid
     * @param hostid
     * @return
     */
    @Override
    public Map<String, Object> getTriggerByHostID(String hostid) {
        final String token = APIUtils.getToken();
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output","triggerids");
                put("hostids",hostid);
                //过滤只筛选有问题的触发器
                put("filter",new HashMap<String,Object>(){{
                    put("value",1);
                }});
            }});
        }};
        Map<String, Object> resultList = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return resultList;
    }


    /**
     * 分页以及返回总的事件
     * @param severities 严重等级
     * @param hostIds 主机id
     * @param curPage 当前页码
     * @param pageSize 当前页的大小
     * @return 分页后的数据
     */
    @Override
    public Map<String, Object> PagingHostList(String severities, String hostIds, String curPage, String pageSize) {
        ProblemServiceImpl problemService = new ProblemServiceImpl();
        // 获得最近告警全部总数
        final int eventCount = Integer.parseInt(problemService.getAllRecentProblemEventsCounts().get("result").toString());
        // 获得全部最近告警事件
        List<Map<String, Object>> pageHostList = problemService.getAllRecentProblemEvents(curPage, pageSize);
        // 进行后端分页处理
        Map<String, Object> resMap = TextUtils.packDataToMap(pageHostList, eventCount);
        return resMap;
    }

    /**
     * 分页以及返回选中的总的事件
     * @param severities 格式化后严重等级字符串
     * @param hostIds 主机 id
     * @param hostNames 主机名
     * @param currentPage 当前页
     * @param pageSize 页面大小
     * @return
     */
    @Override
    public Map<String, Object> PagingAlterHostList(String severities, String hostIds, String hostNames,String currentPage,String pageSize) {
        ProblemServiceImpl problemService = new ProblemServiceImpl();
        // 获取结果集的数目
        final int eventCount = problemService.getAlterAllRecentProblemEventsCounts(severities,hostIds,hostNames).size();
        // 获取结果
        List<Map<String, Object>> pageHostList = problemService.getAlterAllRecentProblemEvents(severities,hostIds,hostNames,currentPage,pageSize);
        // 进行后端分页，格式化数据
        Map<String, Object> resMap = TextUtils.packDataToMap(pageHostList, eventCount);
        return resMap;
    }

    /**
     * 通过triggerid 和 serveries 获得事件
     * @param serveries
     * @param trigger
     * @param hostid
     * @param host
     * @return
     */
    @Override
    public Map<String, Object> getEventByTriggerIDServeries(String serveries, String trigger, String hostid,String host) {
        String token = APIUtils.getToken();
        // 输出过滤
        List<String> itemList = new ArrayList<>();
        itemList.add("source"); //事件产生来源
        itemList.add("name");// 事件名称
        itemList.add("clock");// 事件创建事件
        itemList.add("value");//事件状态 {0:ok 1:problem}
        itemList.add("severity");//事件的安全性
        itemList.add("acknowledged");//事件的确认状态
        itemList.add("object");//与事件对应的对象类型
        itemList.add("objectid");//相关对象id

        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("objectids", trigger);
                put("select_acknowledges","extend");
                put("selectHosts",hostid);
                put("output",itemList);
                put("severities", TextUtils.revertSeverity(serveries));
                put("sortfield","clock");
                put("sortorder","DESC");
            }});
        }};
        Map<String, Object> responseList = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return null;
    }


    /**
     * 获得全部最近告警事件
     * @param curPage
     * @param pageSize
     * @return
     */
    @Override
    public List<Map<String, Object>> getAllRecentProblemEvents(String curPage, String pageSize) {
        String token = APIUtils.getToken();
        int curPages = Integer.parseInt(curPage);
        int pageSizes = Integer.parseInt(pageSize);
        int fin_num = 0;
        ProblemServiceImpl problemService = new ProblemServiceImpl();
        ArrayList<String> itemList = new ArrayList<>();
        ArrayList<String> hostList = new ArrayList<>();
        ArrayList<String> nameList = new ArrayList<>();
        hostList.add("host");
        nameList.add("name");
        itemList.add("triggerid");
        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output",itemList);
                put("filter",new HashMap<String,Object>(){{
                    put("value",1);
                }});
                //put("sortfield","priority");
                put("sortfield","lastchange");
                put("sortorder","DESC");
                put("min_severity",0);
                put("selectHosts",hostList);
                put("selectGroups",nameList);
                put("only_true",0);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        final int eventCount = Integer.parseInt(problemService.getAllRecentProblemEventsCounts().get("result").toString());
        List<Map<String, Object>> responseList = new ArrayList<>();
        if (curPages*pageSizes>eventCount)
            fin_num = eventCount;
        else
            fin_num = curPages * pageSizes;
        for (int i=(curPages-1)*10;i<fin_num;i++){
            String[] str = resultList.get(i).get("hosts").toString().split("\"");
            Map<String,Object> resultTemp = problemService.getEventByTriggerID(resultList.get(i).get("triggerid").toString(),str[3],str[7]);
            responseList.add(resultTemp);
        }
        return responseList;
    }

    /**
     * 获得最近告警全部总数
     * @return
     */
    @Override
    public Map<String, Object> getAllRecentProblemEventsCounts() {
        String token = APIUtils.getToken();
        Map<String,Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "trigger.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("filter",new HashMap<String,Object>(){{
                    put("value",1);
                }});
                put("sortfield","priority");
                put("sortorder","DESC");
                put("min_severity",0);
                put("only_true",0);
                put("countOutput",true);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        return responseMap;
    }

    /**
     * 获得选中最近告警事件总数
     * @param severities
     * @param hostIds
     * @param hostNames
     * @return
     */
    @Override
    public List<Map<String, Object>> getAlterAllRecentProblemEventsCounts(String severities, String hostIds,String hostNames) {
        ProblemServiceImpl problemService = new ProblemServiceImpl();
        String[] hostIdsList = hostIds.split(",");
        String[] hostNamesList = hostNames.split(",");
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (int i=0;i<hostIdsList.length;i++){
            JSONArray array = (JSONArray) problemService.getTriggerByHostID(hostIdsList[i]).get("result");
            for (Iterator iterator = array.iterator(); iterator.hasNext();) {
                JSONObject obj = (JSONObject)iterator.next();
                Map<String,Object> resultMap = problemService.getEventByTriggerID(severities,obj.get("triggerid").toString(),hostNamesList[i],hostIdsList[i]);
                if (resultMap==null)
                    continue;
                resultList.add(resultMap);
            }
        }
        return resultList;
    }

    /**
     * 获得选中最近全部告警
     * @param severities
     * @param hostIds
     * @param hostNames
     * @param currentPage
     * @param pageSize
     * @return
     */
    @Override
    public List<Map<String, Object>> getAlterAllRecentProblemEvents(String severities, String hostIds, String hostNames, String currentPage, String pageSize) {
        ProblemServiceImpl problemService = new ProblemServiceImpl();
        int curPages = Integer.parseInt(currentPage);
        int pageSizes = Integer.parseInt(pageSize);
        int fin_num = 0;
        String[] hostIdsList = hostIds.split(",");
        String[] hostNamesList = hostNames.split(",");
        List<Map<String,Object>> resultList = new ArrayList<>();
        List<Map<String,Object>> PagingresultList = new ArrayList<>();
        for (int i=0;i<hostIdsList.length;i++){
            JSONArray array = (JSONArray) problemService.getTriggerByHostID(hostIdsList[i]).get("result");
            for (Iterator iterator = array.iterator(); iterator.hasNext();) {
                JSONObject obj = (JSONObject)iterator.next();
                Map<String,Object> resultMap = problemService.getEventByTriggerID(severities,obj.get("triggerid").toString(),hostNamesList[i],hostIdsList[i]);
                if (resultMap==null)
                    continue;
                resultList.add(resultMap);
            }
        }
        final int eventCount = resultList.size();
        if (curPages*pageSizes>eventCount)
            fin_num = eventCount;
        else
            fin_num = curPages * pageSizes;
        for(int i=(curPages-1)*10;i<fin_num;i++)
            PagingresultList.add(resultList.get(i));
        return PagingresultList;
    }

    /**
     * 移除一个最近告警事件
     * @param index
     * @return
     */
    @Override
    public Map<String, Object> deleteARecentProblemEvents(String index) {
        ProblemServiceImpl problemService = new ProblemServiceImpl();
        // 获取所有告警事件
        List<Map<String,Object>> resultList = problemService.getAllRecentProblemEvents("1",problemService.getAllRecentProblemEventsCounts().get("result").toString());
        // 从结果中删除
        resultList.remove(Integer.valueOf(index));
        return null;
    }

    @Override
    public List<Map<String, Object>> getAllOnlineHostName(String hostid) {
        final String token = APIUtils.getToken();
        String[] hostidList = hostid.split(",");
        ArrayList<String> imp_str = new ArrayList<>();
        imp_str.add("hostid");
        imp_str.add("host");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("hostids",hostidList);
                put("output",imp_str);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getAllOnlineHostName() {
        final String token = APIUtils.getToken();
        ArrayList<String> imp_str = new ArrayList<>();
        imp_str.add("hostid");
        imp_str.add("host");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "host.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output",imp_str);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }

    @Override
    public List<Map<String, Object>> getProblemByObjectID(String objectid) {
        final String token = APIUtils.getToken();
        ArrayList<String> imp_str = new ArrayList<>();
        imp_str.add("r_ns");
        imp_str.add("r_clock");
        imp_str.add("acknowledged");
        Map<String, Object> paramsMap = new HashMap<String, Object>(){{
            put("jsonrpc", "2.0");
            put("method", "problem.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>(){{
                put("output","extend");
                put("objectids",objectid);
            }});
        }};
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(paramsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>)responseMap.get("result");
        return resultList;
    }

    public Map<String, Object> ignoreknowledgeProblem(String eventId, String desc) {
        final String token = APIUtils.getToken();


        //忽略后此类告警

        Map<String,Object> result=getObjectid(token,eventId);



        if(result!=null&&(result.get("objectid")!=""||!result.get("objectid").equals(""))){
            String objectid=(String)result.get("objectid");

            //忽略后此类告警
            TriggerServiceImpl triggerService = new TriggerServiceImpl();
            result = triggerService.updateTrigger(objectid,"1");

            return result;
        }
        return result;
    }

    @Override
    public Map<String, Object> getObjectid(String token, String eventIds) {
        final String[] outputs = new String[]{
                "enventid", "objectid" };

        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("output", outputs);
            put("eventids", eventIds);
        }};

        // 填入参数
        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};

        // String str2 =JSON.toJSONString(parameterMap);
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
        if(resultList.size()>0)
            return resultList.get(0);
        else return null;
    }

    /**
     * 根据主机hostid获取其当前未处理告警信息，并根据严重等级进行分类
     * (可以同时查询多个主机，但返回结果未根据主机进行分类)
     * @param hostids
     * @return 返回各严重等级对应的告警信息数量
     */
    @Override
    public List<Map<String, Object>> getAlertInformationByHostids(ArrayList<String> hostids) {
        // 令牌获得
        String token = APIUtils.getToken();

        // 数据过滤
        List<String> output = new ArrayList<>();
        output.add("object");
        output.add("objectid");
        output.add("name");
        output.add("r_eventid");
        output.add("severity");
        output.add("acknowledged");

        Map<String, String> searchMap = new HashMap<String, String>() {{
            put("r_eventid", "0");  // 筛选出尚未解决的问题
        }};

        // 请求参数封装
        Map<String, Object> paramsMap = new HashMap<String, Object>() {{
            put("output", output);
            put("acknowledged", false);     // 筛选未被确认的问题
            put("hostids", hostids);

            put("sortfield", "eventid");
            put("sortorder", "DESC");
            put("filter", new HashMap<String, Object>() {{
                put("searchByAny", true);   // 开启筛选
                put("search", searchMap);    // 具体筛选，规则为LIKE "%...%"
                put("startSearch", true);    // 从头开始搜索
            }});
        }};
        Map<String, Object> parameterMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "problem.get");
            put("id", 1);
            put("auth", token);
            put("params", paramsMap);
        }};

        // 发送请求
        Map<String, Object> responseMap = APIUtils.sendRequest(JSON.toJSONString(parameterMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> resultList = (List<Map<String, Object>>) responseMap.get("result");
//        System.out.println(resultList.size());

        // **找出问题事件对应的主机
        String[] eventidArray = new String[resultList.size()];
        for (int i = 0; i < resultList.size(); i++) {
            Map<String, Object> tempMap = resultList.get(i);
            eventidArray[i] = (String) tempMap.get("eventid");
        }
        final String[] selectHosts = new String[]{"host"};
        // 封装参数
        Map<String, Object> eventParamsMap = new HashMap<String, Object>() {{
            put("jsonrpc", "2.0");
            put("method", "event.get");
            put("id", 1);
            put("auth", token);
            put("params", new HashMap<String, Object>() {{
                put("eventids", eventidArray);
                put("selectHosts", selectHosts);
                put("sortfield", "eventid");    // 与前面的problem.get排序规则相同
                put("sortorder", "DESC");   // 同上
            }});
        }};
        // 获取数据
        Map<String, Object> hostsMap = APIUtils.sendRequest(JSON.toJSONString(eventParamsMap, SerializerFeature.WriteMapNullValue));
        List<Map<String, Object>> hostsList = (List<Map<String, Object>>) hostsMap.get("result");
//        System.out.println(hostsList.size());

        // **分别统计不同主机的不同严重性等级事件各有多少
        // 初始化
        List<Map<String,Object>> hostAlertInfor = new ArrayList<>();
        for (int i = 0; i < hostids.size(); i++) {
            Map<String,Object> alertCount = new HashMap<>();
            alertCount.put("hostid",hostids.get(i));
            alertCount.put("alert_count",0);
            alertCount.put("undefine",0);
            alertCount.put("infor",0);
            alertCount.put("alert",0);
            alertCount.put("yibanyanzhong",0);
            alertCount.put("yanzhong",0);
            alertCount.put("zainan",0);
            hostAlertInfor.add(alertCount);
        }
        // 根据严重等级分类
        int count = 0;
        int total = 0;
        if(hostsList != null & hostsList.size() != 0){
            // 带划分信息列表
            for (int i = 0; i < hostsList.size(); i++) {
                // 主机列表
                for (int j = 0; j < hostAlertInfor.size(); j++) {
                    // 主机id匹配
                    if (((List<Map<String, String>>) hostsList.get(i).get("hosts")).get(0).get("hostid").equals(hostAlertInfor.get(j).get("hostid"))) {
                        // 根据严重等级分类 0-未定义 1-信息 2-警告 3-一般严重 4-严重 5-灾难
                        switch (Integer.parseInt((String) hostsList.get(i).get("severity"))) {
                            case 0: {
                                count = (Integer) hostAlertInfor.get(j).get("undefine");
                                hostAlertInfor.get(j).put("undefine", ++count);
                                break;
                            }
                            case 1: {
                                count = (Integer) hostAlertInfor.get(j).get("infor");
                                hostAlertInfor.get(j).put("infor", ++count);
                                break;
                            }
                            case 2: {
                                count = (Integer) hostAlertInfor.get(j).get("alert");
                                hostAlertInfor.get(j).put("alert", ++count);
                                break;
                            }
                            case 3: {
                                count = (Integer) hostAlertInfor.get(j).get("yibanyanzhong");
                                hostAlertInfor.get(j).put("yibanyanzhong", ++count);
                                break;
                            }
                            case 4: {
                                count = (Integer) hostAlertInfor.get(j).get("yanzhong");
                                hostAlertInfor.get(j).put("yanzhong", ++count);
                                break;
                            }
                            case 5: {
                                count = (Integer) hostAlertInfor.get(j).get("zainan");
                                hostAlertInfor.get(j).put("zainan", ++count);
                                break;
                            }
                        }
                        // 计算总计
                        total = (Integer) hostAlertInfor.get(j).get("alert_count");
                        hostAlertInfor.get(j).put("alert_count", ++total);
                    }
                }
            }
        }
        return hostAlertInfor;
    }

    //7天内每天的未处理告警数据
    @Override
    public Map<String, Object> getWeekUnhandledEvents() {

        Map<String, List<Map<String, Object>>> result = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < 7; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            String formatDate = sdf.format(calendar.getTime());
            result.put(formatDate, new ArrayList<Map<String, Object>>());
        }

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);
        Date startTime = calendar.getTime();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间
        String endDate = df.format(new Date());
        //  默认一周，即从当前位置开始后退604,800秒
        String startDate = df.format(startTime);
        // 拿到API数据
        List<Map<String, Object>> problemDataList = reportExportService.getHistoryAlertAndOrder(startDate,endDate);     // 获得排序的历史数据
        for (int i = 0; i < problemDataList.size(); i++) {
            Map<String, Object> stringObjectMap = problemDataList.get(i);
            String date = stringObjectMap.get("clock").toString().split(" ")[0];
            List<Map<String, Object>> list = result.get(date);
            list.add(stringObjectMap);
            result.put(date, list);
        }
        Map<String, Object> fianl_result = new HashMap<>();
        fianl_result.put("result", result);
        return fianl_result;
    }

    //7天内每天的已处理告警总数
    @Override
    public Map<String, Object> getWeekProcessedEvents() {
        final String token = APIUtils.getToken();

        Map<String, Integer> result = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        for (int i = 0; i < 7; i++) {
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.DATE, -i);
            String formatDate = sdf.format(calendar.getTime());
            result.put(formatDate, 0);
        }

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -7);
        Date startTime = calendar.getTime();

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//格式化时间
        String endDate = df.format(new Date());
        //  默认一周，即从当前位置开始后退604,800秒
        String startDate = df.format(startTime);
        // 拿到API数据,拼凑时间戳
        String dateStr = DateUtils.timeToStamp(startDate)+","+DateUtils.timeToStamp(endDate);

        List<Map<String, Object>> problemDataList = getProblems_new(true, "", "", dateStr);

        //跳过系统自动关闭的问题
        for (int i = 0; i < problemDataList.size(); i++) {
            Map<String, Object> resmap = getSolutionByEventId(problemDataList.get(i).get("eventid").toString());
            Map<String, Object>acknowledges = (Map<String, Object>) resmap.get("result");

            // 将以忽略和已处理均作为已处理事件
            if (acknowledges.get("message").equals("此告警项已被忽略")) {
                Map<String, Object> stringObjectMap = problemDataList.get(i);

                String date = DateUtils.SecondTimeStamp2Date(stringObjectMap.get("clock").toString()).split(" ")[0];
                result.put(date, result.get(date)+1);
            }else {
                List<Map<String, Object>> DataList = getProblemByObjectID(problemDataList.get(i).get("objectid").toString());
                if (!DataList.isEmpty() && problemDataList.get(i).get("eventid").equals(DataList.get(0).get("eventid"))) {

                    Map<String, Object> stringObjectMap = problemDataList.get(i);
                    String date = DateUtils.SecondTimeStamp2Date(stringObjectMap.get("clock").toString()).split(" ")[0];
                    result.put(date, result.get(date)+1);
                }
            }
        }


        //result为一个七天日期为键为时间，值为已处理数量(已忽略+已处理)
        Map<String, Object> fianl_result = new HashMap<>();

        //返回结果
        fianl_result.put("result", result);

        return fianl_result;
    }

}
